<template>
  <el-scrollbar height="400px" @scroll="scroll">
    <div v-loading="isShow" v-if="isShow" style="height: 50px;width: 100%;"
      element-loading-background="rgba(122, 122, 122, 0)"></div>
    <view class="item" v-for="item in chatList" :key="item">
      <pcUserMsg :msg="item.dialogueContent" v-if="item.userType === 0">
      </pcUserMsg>
      <appUserMsg :msg="item.dialogueContent" v-else-if="item.userType === 1">
      </appUserMsg>
    </view>
  </el-scrollbar>
</template>

<script setup>
import appUserMsg from './appUserMsg.vue';
import pcUserMsg from './pcUserMsg.vue';
import { ref, onMounted, watch, defineEmits } from 'vue';
import { getChatDialog, Communication } from '../../../api/solution/chat';

const emit = defineEmits(['update:open']);

const chatList = ref([]);
const isShow = ref(false);
const pageTotal = ref(0);
const pageNum = ref(1);
const timer = ref(null);
const props = defineProps({
  dialogId: {
    type: Number,
    default: 0
  },
  open: {
    type: Boolean,
    default: false
  }
});

const initChatList = async () => {
  const res = await getChatList();
  chatList.value = res;
  timer.value = setInterval(getMore, 1000);
};

const getMore = async () => {
  const { data } = await Communication(props.dialogId);
  data.reverse();
  data.forEach((item) => {
    const index = chatList.value.findIndex((chat) => chat.id === item.id);
    if (index === -1) {
      chatList.value.push(item);
    }
  });
};

onMounted(() => {
  initChatList();
});

watch(() => props.open, (newValue) => {
  if (!newValue) {
    clearInterval(timer.value);
    timer.value = null;
  }
});

const scroll = async ({ scrollTop }) => {
  if (scrollTop !== 0 || chatList.value.length >= pageTotal.value) {
    return;
  }
  // 发起请求
  pageNum.value += 1;
  const res = await getChatList();
  chatList.value = [...res, ...chatList.value];
};

async function getChatList() {
  isShow.value = true;
  try {
    const { rows, total } = await getChatDialog({
      pageNum: pageNum.value,
      pageSize: 10,
      dialogueId: props.dialogId
    });
    pageTotal.value = total;
    rows.reverse();
    return rows;
  } finally {
    isShow.value = false;
  }
}

watch(() => props.dialogId, () => {
  clearInterval(timer.value);
  pageNum.value = 1;
  chatList.value = [];
  initChatList();
});
</script>

<style lang="scss" scoped>
.item {
  display: block;
  margin-bottom: 10px;
}
</style>